package com.chuangyang.fixboxmaster.ui;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.chuangyang.fixboxlib.utils.StringUtils;
import com.chuangyang.fixboxlib.widgets.PullDownRefreshListView;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.B2BCostItem;
import com.chuangyang.fixboxmaster.bean.B2BOrder;
import com.chuangyang.fixboxmaster.bean.B2BPart;
import com.chuangyang.fixboxmaster.bean.B2BPartDetail;
import com.chuangyang.fixboxmaster.bean.B2BPartPriceItem;
import com.chuangyang.fixboxmaster.listener.B2BPartNumChangeListener;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.ui.adapter.GetPartAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

/**
 * Created by vanshu on 15/11/7 15:30.
 */
public class GetPartActivity extends BaseActivity implements AdapterView.OnItemClickListener, PullDownRefreshListView.OnRefreshListener, B2BPartNumChangeListener, View.OnClickListener {
    private B2BOrder order;
    private PullDownRefreshListView mListView;
    private GetPartAdapter mAdapter;
    private ArrayList<B2BPart> mb2bPartList = new ArrayList<>();
    private ArrayList<ArrayList<B2BPart>> totalPartList=new ArrayList<>();
    private TextView mTotalPrice;
    private int currentPage = 1;
    private int totalPage;
    private TextView  mPartTotalNum;
    private String isRechoose;
    //TODO 多个配件会记录最后一次的配件bug
    //TODO 总价格显示问题
    //TODO 费用清单下面总价

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_part);
        setTitle("添加配件");
        order = (B2BOrder) getIntent().getSerializableExtra("order");
        isRechoose= getIntent().getStringExtra("isRechoose"); //1
        mListView = (PullDownRefreshListView) findViewById(R.id.part_list);
        TextView mPartName = (TextView) findViewById(R.id.tv_part_name);
        mPartTotalNum = (TextView) findViewById(R.id.tv_part_total_num);
        mTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        Button mBtnOK = (Button) findViewById(R.id.btn_ok);
        Button mBtnNext = (Button) findViewById(R.id.btn_next);
        mBtnOK.setOnClickListener(this);
        mBtnNext.setOnClickListener(this);
        mPartTotalNum.setText(currentPage + "/" + order.PRODUCT_NUMS);
        totalPage = order.PRODUCT_NUMS;
        mPartName.setText(order.PRODUCT_BRAND + order.PRODUCT_NAME + order.PRODUCT_NAME);
        mAdapter = new GetPartAdapter(mb2bPartList);
        mAdapter.setNumberChangeListener(this);
        mListView.setAdapter(mAdapter);
        mListView.setOnRefreshListener(this);
        loadData();
    }


    private Response.Listener<B2BPart.B2BPartInfo> responseListener = new Response.Listener<B2BPart.B2BPartInfo>() {
        @Override
        public void onResponse(B2BPart.B2BPartInfo response) {
            mb2bPartList.addAll(Arrays.asList(response.result.list));
            mAdapter.notifyDataSetChanged();
            if (mb2bPartList.size() >= response.result.totalCount)
                mListView.setLoadingEnd();
            else
                mListView.setLoadingIdle();
        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.contact_enterprise_phone_number_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_contact_phone_number:
                StringUtils.dialPhone(this, order.phoneNumber);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onRefresh() {
        loadData();
    }

    public void loadData() {
        mListView.setLoading();
        loadDataWithoutFootLoading();
    }

    public void loadDataWithoutFootLoading() {
        HashMap<String, String> param = new HashMap<>();
        param.put("id", String.valueOf(order.Id));
        param.put("pageIndex", String.valueOf(mb2bPartList.size()));
        addRequest(new GsonRequest<>(FixBoxApi.GET_PART_LIST, param, B2BPart.B2BPartInfo.class, responseListener));
    }

    private void setTotalPrice() {
        int totalPrice = 0;
        for (B2BPart part : mb2bPartList) {
            totalPrice += part.num * (part.PARTS_PRICE);
        }
        mTotalPrice.setText("合计: ￥" + totalPrice);
    }

    @Override
    public void onChange(B2BPart part) {
        setTotalPrice();
        mAdapter.notifyDataSetChanged();
    }

    public void updateView() {
        ++ currentPage ;
        mPartTotalNum.setText(currentPage + "/" + order.PRODUCT_NUMS);
        totalPartList.add(mb2bPartList);
        mb2bPartList.clear();
        loadData();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_ok:
                saveOrder();
                break;
            case R.id.btn_next:
                if (totalPage >currentPage) {
                    updateView();
                } else {
                    Toast.makeText(GetPartActivity.this, "已经到了最后一页", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    public void saveOrder() {
        totalPartList.add(mb2bPartList);
        String json = getCostItemJson();
        HashMap<String,String> param=new HashMap<>();
        param.put("id", String.valueOf(order.Id));
        param.put("partList",json);
        if(isRechoose!=null&&isRechoose.equals("1")){
            param.put("isRechoose",isRechoose);
        }
        addRequest(new GsonRequest<>(FixBoxApi.GET_PART_LIST_SAVE, param, B2BPartDetail.B2BPartDetailInfo.class, saveResponseListener));
    }

    private String getCostItemJson() {
        ArrayList<B2BCostItem> mCostItemList = new ArrayList<>();
        B2BPartPriceItem item=new B2BPartPriceItem();
        ArrayList<B2BPartPriceItem> mOrderPriceItem = new ArrayList<>();
        for(ArrayList<B2BPart> arrayList :totalPartList){
            for (B2BPart b2BPart : arrayList) {
                B2BCostItem     costItem = new B2BCostItem();
                costItem.title = b2BPart.PARTS_NAME;
                costItem.price = b2BPart.PARTS_PRICE;
                costItem.num = b2BPart.num;
                costItem.partId = Integer.parseInt(b2BPart.Id);
                mCostItemList.add(costItem);
            }
            item.costitem= mCostItemList.toArray(new B2BCostItem[mCostItemList.size()]);
            mOrderPriceItem.add(item);
        }
        Gson gson = new Gson();
        return gson.toJson(mOrderPriceItem);
    }


    private Response.Listener<B2BPartDetail.B2BPartDetailInfo> saveResponseListener = new Response.Listener<B2BPartDetail.B2BPartDetailInfo>() {
        @Override
        public void onResponse(B2BPartDetail.B2BPartDetailInfo response) {
            if(response.success==1){
                finish();
            }
        }
    };
}
